library(dplyr)
library(ggplot2)

#### Load dataset ####
dataset <- read_rds("dataset_leip_dataverse.rds")


#### PREP DATA ####

## Set `pcteligible2013` to % value
dataset <- dataset %>% 
  mutate(pcteligible2013 = pcteligible2013 * 100)

## Create dataframe for the four graphs
df3 <- dataset %>%
  select(dregistration20142010,
         dregistration20162012,
         dturnout20142010,
         dturnout20162012,
         pcteligible2013,
         z
         ) %>%
  mutate(z = if_else(z == 0, "Not Expanding", "Expanding")) %>%
  mutate(z_f = factor(
    dataset_fig3$z, levels = c("Not Expanding", "Expanding")))



#### PLOT DATA ####

## Create list of titles for each graph
titles <- c("Registration 2014 - 2010",
            "Registration 2016 - 2012",
            "Turnout 2014 - 2010",
            "Turnout 2016 - 2012")

plot_list <- list()


## For loop 
for(i in 1:4){
  # Store data in column i as y
  #y = df3[,i]
  
  # Plot scatter plot of d
  plot <- df3 %>%
    ggplot(aes(x = pcteligible2013,
               y = df3[,i])) +
    facet_grid(. ~ z_f) +
    geom_point(color = "lightgray") +
    scale_x_continuous(limit = c(0, 60)) +
    scale_y_continuous(limit = c(-20, 10)) +
    labs(
      x = "Potential Eligibility",
      y = "Change in Participation",
      title = (paste(titles[i]))
    ) +
    
    # Customize appearance
    theme_classic() +
    theme(axis.line = element_line(size = 0.25),
          strip.background = element_rect(colour = "white", fill = "white"),
          plot.title = element_text(hjust = 0.5)) +
    
    ## Add regression line 
    stat_smooth(method = "lm",
                col = "black",
                se = FALSE,
                size = 0.7)
  
  ## Save each plot to plot_list
  plot_list[[i]] <- plot
}

## Save plots - makes a separate file for each plot.
for (i in 1:4) {
  file_name = paste("Plot", i, ".jpg", sep="")
  tiff(file_name)
  print(plot_list[[i]])
  dev.off()
}


## Create grid of four plots
figure1 <- do.call(grid.arrange, plot_list)

## Save to png
ggsave(file = "figure1.png", plot = figure1)



